
//preloading.....
load("library/common.js");

JEuler.system.loadJS("library/math.js");

//(function() {

    //JEuler.system.loadJS("data/???.dat");
    JEuler.system.printCaption("70");
    JEuler.system.startTimerCount();
    
    JEuler.math.PrimeUtils.sievePrime(Math.floor(Math.pow(10,7/2)));
    JEuler.math.PrimeUtils.printCachedPrimes("v");
    var primes = JEuler.math.PrimeUtils.getPrimePool();
    
    function getFactors(n) {
        if(JEuler.math.PrimeUtils.isPrime(n)) return [n];
        var tmp = n, result=[];
        for(var i=0; i<primes.length; i++) {
            var p = primes[i];
            if(tmp<p) return result;
            if(tmp%p==0) result.push(p);
            while(tmp%p==0) {
                tmp = tmp/p
            }
        }
        return result;
    }
    
    function phi(n, factors) {
        var v=n;
        factors = factors || getFactors(n);
        for(var i=0; i<factors.length; i++) {
            v = v - v /factors[i]
        }
        return v;
    }
    
    function testPermutation (a,b) {
        return a.toString().split("").sort().join("") == b.toString().split("").sort().join("")
    }
    
    var limit = Math.pow(10,7), min=100, factors, n, p;
    for(var i=primes.length-2; i>=0; i--) {
        for(var j=i+1; j<primes.length; j++) {
            n = primes[i]*primes[j];
            if(n>limit) break;
            //factors = getFactors(n); p = phi(n, factors); 
            p = (primes[i]-1)*(primes[j]-1);
            
            if(n/p<min && testPermutation(n, p)) {
                print(n + "," + p + "," +(n/p));
                //print(factors);
                min = n/p;
            }
        }
    }

    JEuler.system.printTimerCount();
    
//})();
